package com.ln.adoms.action;

import com.ln.core.security.entity.Resources;
import com.ln.core.security.entity.ResourcesGroup;
import com.ln.core.security.entity.Users;
import com.ln.core.security.service.ResourcesService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by xi on 14-5-9.
 */
@Controller
public class MainAction {

    @Resource
    private ResourcesService resourcesService;

    @RequestMapping("/login.html")
    public String login(HttpSession session, Model model) {
        return "/login";
    }

    @RequestMapping("/main.html")
    public String main(HttpSession session, Model model) {

        Users USER = (Users) session.getAttribute("USER");

        Map<Object, Object> groupMap = new LinkedHashMap<Object, Object>();
        Map<Object, Object> menuMap = new LinkedHashMap<Object, Object>();

        List<Resources> setResuorces = resourcesService.findMenu(USER.getId());
        for (Resources r : setResuorces) {
            // 是菜单项才添加
            if (r.isMenu()) {
                ResourcesGroup group = r.getGroup();
                // 是菜单项才添加
                if (group.isMenu()) {
                    groupMap.put(group.getId().toString(), group);

                    @SuppressWarnings("unchecked")
                    List<Resources> list = (ArrayList<Resources>) menuMap.get(group.getId().toString());
                    if (list == null) {
                        list = new ArrayList<Resources>();
                    }
                    list.add(r);
                    menuMap.put(group.getId().toString(), list);
                }
            }
        }

        model.addAttribute("groupMap", groupMap);
        model.addAttribute("menuMap", menuMap);
        return "/main";
    }

    @RequestMapping("/content/{gid}.html")
    public String content(HttpSession session, Model model, @PathVariable("gid") Integer gid) {

        Users USER = (Users) session.getAttribute("USER");

        ResourcesGroup group = null;
        List<Resources> resourcesList = new LinkedList<Resources>();

        List<Resources> setResuorces = resourcesService.findMenu(USER.getId());
        for (Resources r : setResuorces) {
            // 是菜单项才添加
            if (r.isMenu()) {
                ResourcesGroup rGroup = r.getGroup();
                // 是菜单项才添加
                if (rGroup.getId().equals(gid) && rGroup.isMenu()) {
                    group = rGroup;
                    resourcesList.add(r);
                }
            }
        }

        model.addAttribute("group", group);
        model.addAttribute("resourcesList", resourcesList);
        return "/content";
    }
}
